package com.atguigu.flinkSql;

import com.atguigu.been.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Slide;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.*;

/**
 * @author wky
 * @create 2021-07-21-9:21
 */

//基于文件个数
public class Flink16_TableApi_Window_CountWindow {
    public static void main(String[] args) throws Exception {
        //创建流执行环境
        //创建流执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> watermarks = env.fromElements(
                new WaterSensor("sensor_1", 1000L, 10),
                new WaterSensor("sensor_1", 2000L, 20),
                new WaterSensor("sensor_2", 3000L, 30),
                new WaterSensor("sensor_1", 4000L, 40),
                new WaterSensor("sensor_1", 5000L, 50),
                new WaterSensor("sensor_2", 6000L, 60),
                new WaterSensor("sensor_2", 6000L, 60),
                new WaterSensor("sensor_2", 6000L, 60),
                new WaterSensor("sensor_2", 6000L, 60),
                new WaterSensor("sensor_2", 6000L, 60),
                new WaterSensor("sensor_2", 6000L, 60),
                new WaterSensor("sensor_2", 6000L, 60)
                )
                .assignTimestampsAndWatermarks(WatermarkStrategy.
                        <WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                        .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                            @Override
                            public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                                return element.getTs();
                            }
                        }));
        //创建表执行环境
        StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env);
        //TODO 读取数据 建立基于文件个数的滑动窗口
        //.window(Session.withGap(lit(6).second()).on($("ts")).as("w") 会话窗口
//        Table table = tableEnvironment.fromDataStream(watermarks, $("id"), $("ts").rowtime(), $("vc")) ; 事件个数不支持 事件时间
        Table table = tableEnvironment.fromDataStream(watermarks, $("id"), $("pt").proctime(), $("vc"));
        table
                .window(Slide.over(rowInterval(4L)).every(rowInterval(2L)).on($("pt")).as("w"))
                .groupBy($("id"),$("w"))
                .select($("id"),$("vc").sum())
                .execute().print();

        env.execute();

    }
}
